package com.wbao.dianniu.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.MapSearchHelper;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 地图搜索
 *
 * @author yejianjun
 */
public class MapSearchActivity extends Activity implements OnClickListener, OnGetSuggestionResultListener {

    private SuggestionSearch mSuggestionSearch = null;
    private List<HashMap<String, String>> suggest = new ArrayList<>();
    /**
     * 搜索关键字输入窗口
     */
    private AutoCompleteTextView keyWorldsView = null;
    private SimpleAdapter sugAdapter;

    private Button mButton;
    MapView mMapView = null;
    private ListView mapResult;


    class City {
        public String city;
        public String district;
        public String key;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }
        setContentView(R.layout.activity_map_search);
        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
        mapResult = (ListView) findViewById(R.id.map_search_listview);
        keyWorldsView = (AutoCompleteTextView) findViewById(R.id.map_search_edit);
        mButton = (Button) findViewById(R.id.map_search_cancel);
        mButton.setOnClickListener(this);

        sugAdapter = new SimpleAdapter(this, suggest, R.layout.simple_map_list_item, new String[]{"key", "city_district"}, new int[]{R.id.key_tv, R.id.city_district});
        mapResult.setAdapter(sugAdapter);
        keyWorldsView.addTextChangedListener(watcher);
        mapResult.setOnItemClickListener(itemClick);

        keyWorldsView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = keyWorldsView.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > keyWorldsView.getWidth() - keyWorldsView.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    keyWorldsView.setText("");
                }
                return false;
            }
        });

        String address = getIntent().getStringExtra(CreateActivity.RET_ADDRESS);
        if (!TextUtils.isEmpty(address)) {
            keyWorldsView.setText(address);
            /**
             * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
             */
            mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                    .keyword(address).city(GlobalContext.curLocation));
        }


    }

    OnItemClickListener itemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            MapSearchHelper.getInstance().searchPosition(suggest.get(position).get("city"), suggest.get(position).get("key"));
//            MapActivity.searchButtonProcess(suggest.get(position).get("city"), suggest.get(position).get("key"));
            finish();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.map_search_cancel:
                this.finish();
                break;
            default:
                break;
        }
    }

    /**
     * 当输入关键字变化时，动态更新建议列表
     */
    TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int start, int before, int count) {
            if (cs.length() <= 0) {
                return;
            }
            /**
             * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
             */
//            System.out.println("city is :" + GlobalContext.curLocation);
            mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                    .keyword(cs.toString()).city(GlobalContext.curLocation));
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    @Override
    protected void onDestroy() {
        mSuggestionSearch.destroy();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    /**
     * 获取在线建议搜索结果，得到requestSuggestion返回的搜索结果
     *
     * @param res
     */
    @Override
    public void onGetSuggestionResult(SuggestionResult res) {
        // TODO Auto-generated method stub
        if (res == null || res.getAllSuggestions() == null) {
            return;
        }
        suggest = new ArrayList<HashMap<String, String>>();
        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
            if (info.key != null && !info.key.equals("")) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("city_district", info.city + info.district);
                map.put("city", info.city);
                map.put("key", info.key);
                suggest.add(map);
            }
        }
        sugAdapter = new SimpleAdapter(this, suggest, R.layout.simple_map_list_item, new String[]{"key", "city_district",}, new int[]{R.id.key_tv, R.id.city_district});
        mapResult.setAdapter(sugAdapter);
        sugAdapter.notifyDataSetChanged();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
